import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt

# 读取.tsv文件
@st._cache_resource
def load_data():


    # df = pd.read_csv('cleaned_data.tsv', sep='\t')

    df = pd.read_csv('cleaned_data.tsv', sep='\t', low_memory=False)
    df['recTime'] = pd.to_datetime(df['recTime'])
    return df

df = load_data()

# 根据用户选择的字段绘制动态图表
def plot_dynamic_chart(df, column):
    # 按照时间顺序对数据集进行排序
    df_sorted = df.sort_values(by='recTime')
    counts = df_sorted[column].value_counts()

    # 创建Matplotlib图形对象
    fig, ax = plt.subplots(figsize=(10, 6))
    ax.plot(counts.index, counts.values)
    ax.set_xlabel('Time')
    ax.set_ylabel('Count')
    ax.set_title(f'{column} Counts Over Time')
    ax.tick_params(axis='x', rotation=45)


    # 以条形图的方式展示workMode字段的分布情况
    st.subheader('recTime Distribution')
    st.bar_chart(df['recTime'].value_counts())
    #
    # # 以扇形图的方式展示recResult字段的分布情况
    # st.subheader('recResult Distribution')
    # st.pyplot(plt.figure(figsize=(8, 8)))
    # df['recResult'].value_counts().plot(kind='pie', autopct='%1.1f%%')
    # st.pyplot()


    # 将Matplotlib图形对象传递给st.pyplot()函数
    st.pyplot(fig)

# 主界面
st.title('Data Analysis and Visualization')

# 显示数据集的摘要信息
st.write('## Dataset Summary')
st.write(df.head())

# 选择字段绘制动态图表
selected_column = st.selectbox('Select a column to visualize:', df.columns)
plot_dynamic_chart(df, selected_column)
